<template>
  <div class="container mt-4">
    <!-- 页面标题 -->
    <div class="header">
      <h2>物业列表管理</h2>
      <p class="description">在这里查看、添加、编辑或删除物业信息。</p>
    </div>

    <!-- 添加按钮 -->
    <div class="action-container mb-3">
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">添加物业</el-button>
    </div>

    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
        v-model="searchQuery"
        placeholder="请输入物业名称或地址进行搜索"
        clearable
        prefix-icon="el-icon-search"
        class="search-input"
      />
    </div>

    <!-- 表格 -->
    <div class="table-responsive">
      <el-table
        :data="paginatedData"
        :key="tableKey"
        border
        class="table"
        style="width: 100%; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);"
      >
        <el-table-column prop="id" label="物业ID"></el-table-column>
        <el-table-column prop="name" label="物业名称"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <div class="button-group">
              <el-button
                size="mini"
                @click="handleEdit(scope.row)"
                type="primary"
                icon="el-icon-edit"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                icon="el-icon-delete"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <el-pagination
      v-if="filteredData.length > 0"
      background
      layout="prev, pager, next, jumper"
      :total="filteredData.length"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px;"
    />
    
    <!-- 编辑模态框 -->
    <el-dialog v-model="editDialogVisible" title="编辑物业信息" width="50%">
      <el-form :model="currentEdit" label-width="100px" :rules="editRules" ref="editForm">
        <el-form-item label="物业名称" prop="name">
          <el-input v-model="currentEdit.name" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="currentEdit.address" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </el-dialog>

    <!-- 添加物业模态框 -->
    <el-dialog v-model="addDialogVisible" title="添加物业信息" width="50%">
      <el-form :model="newProperty" label-width="100px" :rules="addRules" ref="addForm">
        <el-form-item label="物业名称" prop="name">
          <el-input v-model="newProperty.name" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="newProperty.address" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdd">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { ref, computed, onMounted } from "vue";
import { ElMessage } from 'element-plus';

export default {
  setup() {
    const token = ref(localStorage.getItem("token"));
    const properties = ref({ data: [] });
    const tableKey = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const searchQuery = ref("");
    const editDialogVisible = ref(false);
    const addDialogVisible = ref(false); // 用于控制添加物业模态框的显示
    const currentEdit = ref({});
    const newProperty = ref({ name: '', address: '' });

    const editForm = ref(null);
    const addForm = ref(null);

    // 表单验证规则
    const editRules = {
      name: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
      address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
    };

    const addRules = {
      name: [{ required: true, message: "物业名称不能为空", trigger: "blur" }],
      address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
    };

    const fetchProperties = async () => {
      if (token.value) {
        try {
          const response = await axios.get("http://localhost:3008/buildings", {
            headers: { Authorization: `Bearer ${token.value}` },
          });
          properties.value.data = response.data.data || [];
          tableKey.value++;
        } catch (error) {
          ElMessage.error("服务器连接失败，请稍后再试。");
          properties.value.data = [];
        }
      } else {
        ElMessage.error("未登录或登录已过期，请重新登录。");
        properties.value.data = [];
      }
    };

    const filteredData = computed(() => {
      const lowerQuery = searchQuery.value.toLowerCase();
      return properties.value.data.filter(
        (item) =>
          item.name.toLowerCase().includes(lowerQuery) ||
          item.address.toLowerCase().includes(lowerQuery)
      );
    });

    const paginatedData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredData.value.slice(start, end);
    });

    const handlePageChange = (page) => {
      currentPage.value = page;
    };

    // 编辑物业信息
    const handleEdit = (row) => {
      currentEdit.value = { ...row };
      editDialogVisible.value = true;
    };

    // 保存编辑的物业信息
    const saveEdit = async () => {
      try {
        await editForm.value.validate();
        const response = await axios.put(
          `http://localhost:3008/buildings/${currentEdit.value.id}`,
          currentEdit.value,
          { headers: { Authorization: `Bearer ${token.value}` } }
        );
        if (response.status === 200) {
          const index = properties.value.data.findIndex(
            (item) => item.id === currentEdit.value.id
          );
          if (index !== -1) {
            properties.value.data[index] = { ...currentEdit.value };
            ElMessage.success("物业信息更新成功");
          }
          editDialogVisible.value = false;
        }
      } catch (error) {
        ElMessage.error(`编辑失败: ${error.message}`);
      }
    };

    // 删除物业
    const handleDelete = async (row) => {
      if (confirm(`确定删除物业 ${row.name} 吗？`)) {
        try {
          const response = await axios.delete(`http://localhost:3008/buildings/${row.id}`, {
            headers: { Authorization: `Bearer ${token.value}` },
          });
          ElMessage.success(response.data.message);
          fetchProperties(); // 重新获取物业列表
        } catch (error) {
          ElMessage.error(`删除失败: ${error.message}`);
        }
      }
    };

    // 打开添加物业模态框
    const handleAdd = () => {
      newProperty.value = { name: '', address: '' }; 
      addDialogVisible.value = true;
    };

    // 保存添加的物业信息
    const saveAdd = async () => {
      try {
        await addForm.value.validate();
        const response = await axios.post(
          "http://localhost:3008/buildings",
          newProperty.value,
          { headers: { Authorization: `Bearer ${token.value}` } }
        );
        if (response.status === 200) {
          properties.value.data.push(response.data);
          ElMessage.success("物业信息添加成功");
          addDialogVisible.value = false;
        }
      } catch (error) {
        ElMessage.error(`添加失败: ${error.message}`);
      }
    };

    onMounted(fetchProperties);

    return {
      properties,
      tableKey,
      currentPage,
      pageSize,
      searchQuery,
      paginatedData,
      filteredData,
      handlePageChange,
      handleEdit,
      saveEdit,
      handleDelete,
      editDialogVisible,
      currentEdit,
      editForm,
      addDialogVisible,
      newProperty,
      addForm,
      handleAdd,
      saveAdd,
      editRules,
      addRules,
    };
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 26px;
  color: #333;
  margin-bottom: 8px;
}

.header .description {
  font-size: 14px;
  color: #777;
}

.action-container {
  text-align: right;
}

.search-container {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.search-input {
  max-width: 500px;
  width: 100%;
}

.table-responsive {
  overflow-x: auto;
  margin-bottom: 20px;
}

.el-table {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table tr:hover {
  background-color: #f5f7fa;
}

.el-table th {
  background-color: #f0f2f5;
}

.el-button {
  margin-right: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.button-group {
  display: flex;
  gap: 10px;
}
</style>
